package Terminal.View;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import javax.swing.JDialog;
import java.awt.event.ActionListener;

import com.toedter.calendar.JCalendar;
import com.toedter.calendar.JDateChooser;

public abstract class JCalendario implements ActionListener {

	private JCalendar calendario;
	private JDialog calendarioDialog;
	
	public final JCalendario cal = this;
	public final DateFormat df = new SimpleDateFormat("dd/MM/yyyy");// kk:mm:ss");
	
	public JCalendario()
	{}
	
	public JCalendario(String inizio, String fine)
	{
		this.setDateRange(inizio, fine);
	}
	
	public void actionPerformed(ActionEvent e){
		
		this.setCalendario();
		this.setDialog();

	}
	
	protected abstract void azione(String data);
	
	private void setCalendario()
	{
		calendario = new JCalendar(Locale.ITALIAN);
		
		cal.azione( df.format(calendario.getDate()) );
		
		calendario.addPropertyChangeListener
		(		
			new PropertyChangeListener() 
			{	
				@Override
				public void propertyChange(PropertyChangeEvent evt) 
				{
					if (calendario != null) 
					{
						if (evt.getPropertyName().equals("calendar")) 
					    {
					        Calendar data = (Calendar) evt.getNewValue();
					        
					        String date = df.format(data.getTime());
					        cal.azione(date);
					    }
					}
				}
				
			}
		);
		calendario.setVisible(true);
	}
	
	private void setDialog()
	{
		TimeLoggingFrame t = TimeLoggingFrame.istanza();
		
		calendarioDialog = new JDialog(t, true);		
		calendarioDialog.getContentPane().add(calendario,BorderLayout.CENTER);
		calendarioDialog.setLocation(300,300);
		
		calendarioDialog.pack();
		calendarioDialog.setVisible(true);
	}
	
	public void setDateRange(String inizio, String fine)
	{
		if (inizio != null)
		    try { calendario.setMinSelectableDate( df.parse(inizio) ); }
		    catch (ParseException e) {	// TODO Auto-generated catch block
				e.printStackTrace();
			}
		if (fine != null)
		    try { calendario.setMaxSelectableDate( df.parse(fine) ); }
		    catch (ParseException e) {	// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
	public void setDateInizio(String inizio)
	{
		if (inizio != null)
		    try { calendario.setMinSelectableDate( df.parse(inizio) ); }
		    catch (ParseException e) {	// TODO Auto-generated catch block
				e.printStackTrace();
			}		
	}
	
	public void setDateFine(String fine)
	{
		if (fine != null)
		    try { calendario.setMaxSelectableDate( df.parse(fine) ); }
		    catch (ParseException e) {	// TODO Auto-generated catch block
				e.printStackTrace();
			}		
	}
}
